docs: show how to handle redirects from shared helpers in command functions#16328
docs: show how to handle redirects from shared helpers in command functions#16328Nic-Polumeyv wants to merge 1 commit into
Conversation
|
Install the latest version of pnpm add https://pkg.svelte.dev/@sveltejs/kit/c/c4ad7d7c2b24b26840bfe21ad390bd5a0de379c0Open in Note This PR is from a fork. A maintainer must approve approve each commit before it can be built and installed. |
|
|
You know... I think we've been thinking about this all wrong. My first reaction was that perhaps we should just throw the redirect to the caller... <!--- file: src/routes/+page.svelte --->
<script>
import { isRedirect } from '@sveltejs/kit';
import { goto } from '$app/navigation';
import { addTodo } from './todos.remote';
async function add(text) {
try {
await addTodo(text);
} catch (e) {
if (isRedirect(e)) {
goto(result.redirect);
} else {
throw e;
}
}
}
</script>...and I do think we should do that, but not because it's a In render (i.e. in the template, or while otherwise running an effect), a thrown redirect should cause a Outside render (i.e. in an event handler), it should be like any other exception, and you should have to catch it. The reason for this becomes clear when you consider what currently happens with queries: const todo = await getTodo(id);
console.log(todo.text);If This is one of those deeply-obvious-in-retrospect things — it should allow some simplification of the code, and will make commands behave the same as other remote functions with respect to redirects. Working on this locally. |
|
I can redo this against your change once it's up, since #16275 will still want a docs example either way, or just close it if docs are part of your change. |
|
Docs will need to be part of the other PR, so I'll go ahead and close this — thanks |
Fixes #16275.
The docs promote shared
getRequestEvent()helpers, and the canonicalrequireLogin()example throwsredirect(), which explodes with a confusing client error when reused inside acommand. This expands the existing Redirects section with the intended pattern, catch withisRedirectand return the location for the client togoto.For context, allowing
redirect()insidecommand()natively was floated by Conduitry on #14858 and didn't get maintainer buy-in, so this documents the intended pattern rather than a stopgap.